use std::process::{Command, Child};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use once_cell::sync::Lazy;
use crate::get_path::get_path;
use super::MediaType;
use std::vec::Vec;
use crate::GLOBAL_RUNTIME;
use super::volume::get_volume;
use std::process::Stdio;

static AUDIO_SDP_PATH: Lazy<PathBuf> = Lazy::new(|| {
    get_path().join("sdp").join("AudioSDP.sdp")
});
static VIDEO_SDP_PATH: Lazy<PathBuf> = Lazy::new(|| {
    get_path().join("sdp").join("VideoSDP.sdp")
});

#[derive(Clone)]
pub struct PlayerManager {
    processes: Arc<Mutex<Vec<Child>>>, // 存储所有播放进程
}

impl PlayerManager {
    pub fn new() -> Self {
        PlayerManager {
            processes: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub async fn play_sdp(&self, media_type: MediaType) -> Result<()> {
        let path_str: String;
        let mut ffplay_args: Vec<String> = Vec::new();

        match media_type {
            MediaType::Video => {
                path_str = VIDEO_SDP_PATH.to_str().unwrap().to_string();
                ffplay_args.push("-protocol_whitelist".into());
                ffplay_args.push("file,udp,rtp".into());
                ffplay_args.push("-i".into());
                ffplay_args.push(path_str.clone());
                ffplay_args.push("-fs".into()); // 全屏
            }
            MediaType::Audio => {
                path_str = AUDIO_SDP_PATH.to_str().unwrap().to_string();
                let volume = get_volume().await.to_string();
                ffplay_args.push("-protocol_whitelist".into());
                ffplay_args.push("file,udp,rtp".into());
                ffplay_args.push("-i".into());
                ffplay_args.push(path_str.clone());
                ffplay_args.push("-nodisp".into());
                ffplay_args.push("-volume".into());
                ffplay_args.push(volume);
            }
        }

        let child = Command::new("ffplay")
            .args(ffplay_args)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()?; // 非阻塞启动

        let mut list = self.processes.lock().unwrap();
        list.push(child);

        Ok(())
    }

    pub async fn stop_all(&self) {
        let mut list = self.processes.lock().unwrap();
        for child in &mut *list {
            let _ = child.kill();
        }
    }
}
